import Taro, {useState, useEffect, useCallback, FC} from '@tarojs/taro'
import {View, Text, Image, Canvas, ScrollView} from '@tarojs/components'
import './index.scss'
import {AtTabs, AtTabsPane} from 'taro-ui'
import MarriageBox from '../../components/MarriageBox'
import ABlindDateBox from '../../components/ABlindDateBox'

import CanvasPage from '../../components/canvasPage'
import CanvasPageContext from '../../components/operCanvasPage'
import BackTop from '../../components/backTop'
import {useVisible} from './canvasData'
import loveLornUser from '../../api/lovelorn-user'
import PullDownUp from '../../components/pulldown'
import LOADING_ICONS from '@components/pulldown/load.png'
const titlebg = require('../../assets/seeking/title.png')
import {getGlobalData, setGlobalData} from '../../utils/global'

const MaleBg = ['#5781F8', '#00A3FF', '#06D1D8', '#7F67F8', '#5781F8']
const FeMaleBg = ['#FC5074', '#FF7865', '#FF972F', '#B467F5', '#FC5074']

const tabList = [
  {
    title: '单身男嘉宾',
  },
  {
    title: '单身女嘉宾',
  },
]
const Home: FC = () => {
  const [activeIndex, setActiveIndex] = useState(1)
  const [isToggle, setIsToggle] = useState(false)
  const [seekingList, setSeekingList] = useState([])
  const [visible, setVisible] = useVisible()
  const [clickData, setClickData] = useState({})
  const [titleBg, setTitleBg] = useState('')
  const [hasMore, setHasMore] = useState(true)
  const [noMoreData, setNoMoreData] = useState(false)
  const [loadOver, setLoadOver] = useState(false)
  const [isEmpty, setIsEmpty] = useState(false)
  const [pageNo, setPageNo] = useState(1)
  const [selectItem, setSelectItem] = useState([])
  const [windowheight, setWindowHeight] = useState(getGlobalData('windowHeight'))
  const [maleBg, setMaleBg] = useState([''])
  const [isHide, setIsHide] = useState(false)
  const [isShow, setIsShow] = useState(false)
  const [scrollHeight, setScrollHeight] = useState(0)
  const [scrollTop, setScrollTop] = useState(0)
  const [seekingId, setSeekingId] = useState(0)
  const closeDialoge = () => {
    setIsShow(false)
    setIsHide(false)
  }

  const changeScrollTop = e => {
    setScrollHeight(e)
  }

  const handleClick = useCallback(
    e => {
      setActiveIndex(e + 1)
      console.log(e, 'e')
      setPageNo(1)
    },
    [activeIndex],
  )
  const [userInfo, setUserInfo] = useState(
    getGlobalData('loginVO') ? getGlobalData('loginVO').user : {},
  )
  useEffect(() => {
    Taro.showShareMenu({
      withShareTicket: true,
    })
    Taro.getStorage({
      key: 'loginVO',
      success: function(res) {
        setUserInfo(res.data.user)
      },
    })
  }, [])

  useEffect(() => {
    Taro.downloadFile({
      url: 'http://sl-mo.yryz.com/static/imgs/title.png',
      success: function(res) {
        console.log(res.tempFilePath, 'aaa')
        setTitleBg(res.tempFilePath)
      },
    })
  }, [])
  useEffect(() => {
    getOriginData(1, activeIndex)
  }, [activeIndex])
  const getOriginData = async (No, gender) => {
    try {
      const res = await loveLornUser.marriageSeekingMessages.page({
        gender: gender,
        pageSize: 10,
        pageNo: No,
      })
      Taro.hideLoading()
      if (res && res.records && res.records.length) {
        if (res.records.length < 10) {
          setNoMoreData(true)
          setHasMore(false)
        }
        setLoadOver(true)
        setNoMoreData(false)
        if (No == 1) {
          setSeekingList(res.records)
        } else {
          setSeekingList([...seekingList, ...res.records])
        }
      } else {
        setLoadOver(true)
        setNoMoreData(true)
        setHasMore(false)
        if (No == 1) {
          setSeekingList([])
          setIsEmpty(true)
        } else {
          setSeekingList([...seekingList, ...res.records])
        }
      }
    } catch (ex) {
      console.error(JSON.parse(ex))
    }
  }
  const renderText = content => {
    let arr = content.split('')
    let str = ''
    for (var i = 0; i < arr.length; i++) {
      if (i < 68) {
        str += arr[i]
      }
    }
    return <Text>{str}...</Text>
  }

  const renderAllText = content => {
    return <Text>{content}</Text>
  }
  const showPoster = useCallback(
    (el, index) => {
      console.log(el, 'el')
      if (el.gender == 1) {
        el.background = MaleBg[index]
      } else if (el.gender == 2) {
        el.background = FeMaleBg[index]
      }
      setClickData(() => {
        return el
      })
      setVisible(() => {
        return true
      })
      console.log('showPoster')
    },
    [visible],
  )
  const hidePoster = () => {
    setVisible(false)
  }

  const clickMenu = () => {}
  const source = () => {}

  const close = () => {}

  const expandSingle = useCallback(kid => {
    setSelectItem(items => {
      let hasCheck = items.some(t => t === kid)
      if (hasCheck) {
        return items.filter(t => t !== kid)
      }
      console.log([...items, kid], 'aaaa')
      return [...items, kid]
    })
  }, [])
  const pulldownToloadMore = () => {
    setHasMore(true)
    // setStartPull(true)
    getOriginData(pageNo + 1, activeIndex)
    setPageNo(pageNo + 1)
  }
  const navoDetail = el => {
    Taro.navigateTo({
      url: `/pages/MenberHomePage/index?toUserId=${el.userId}`,
    })
  }

  const inviteBlind = async el => {
    try {
      let res = await loveLornUser.serviceProgress.checkNeed()
      if (!res) {
        setIsHide(true)
        setSeekingId(el.kid)
      } else {
        Taro.showToast({
          title: '你已提交过工单信息，请前往app查看',
          icon: 'none',
        })
      }
    } catch (ex) {
      console.log(ex, 'ex')
    }
  }

  return (
    <CanvasPageContext.Provider value={{clickMenu, close}}>
      <View className="HomePage">
        <View
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            width: '100%',
            height: '100%',
          }}>
          <CanvasPage
            source={clickData}
            titleBg={titleBg}
            visible={visible}
            hidePoster={hidePoster}
          />
        </View>
        <View className="seekingWrap">
          <View className="seekingTitle">
            <View className="seekingTab">
              <Text className={['seekingText', activeIndex == 1 ? 'active' : '']}>单身男嘉宾</Text>
              {activeIndex == 1 && (
                <Image
                  src={require('../../assets/seeking/he.png')}
                  className="topColor leftTitle"
                />
              )}
            </View>
            <View className="seekingTab">
              <Text className={['seekingText', activeIndex == 2 ? 'active' : '']}>单身女嘉宾</Text>
              {activeIndex == 2 && (
                <Image
                  src={require('../../assets/seeking/she.png')}
                  className="topColor rightTitle"
                />
              )}
            </View>
          </View>
          <AtTabs
            animated
            scroll
            current={activeIndex - 1}
            onClick={e => {
              handleClick(e)
            }}
            tabList={tabList}>
            {tabList.map((elItem, elIndex) => {
              return (
                <AtTabsPane current={activeIndex - 1} index={elIndex} key={`index${elIndex}`}>
                  <PullDownUp
                    hasMore={hasMore}
                    noMoreData={noMoreData}
                    onLoadMore={() => {
                      pulldownToloadMore()
                    }}
                    scrollViewHeight={windowheight || 650}
                    isEmpty={isEmpty}
                    // scrollTop={scrollTop}
                    emptyText="暂无数据哦~"
                    emptyDefault="https://cdn.yryz.com/mini-program/image/empty/no_order.png"
                    scrollTop={scrollTop}
                    changeScrollTop={changeScrollTop}>
                    {!loadOver && seekingList.length == 0 && (
                      <View className="load-more-view">
                        <Image className="load-more-icon loading" src={LOADING_ICONS} />
                        <View className="load-more-text">加载中</View>
                      </View>
                    )}
                    {loadOver &&
                      seekingList.map((el: any, index) => {
                        let isToggleStatus = selectItem.some(t => t == el.kid)
                        return (
                          <View
                            className="seekingList"
                            key={`index${index}`}
                            style={{
                              background:
                                el.gender == 1 ? `${MaleBg[index]}` : `${FeMaleBg[index]}`,
                            }}>
                            <View className="seekingSubTitle" onClick={() => navoDetail(el)}>
                              <Text>{el.seekingDescription}</Text>
                              <Text
                                className="rightIcon"
                                onClick={e => {
                                  e.stopPropagation()
                                  showPoster(el, index)
                                }}>
                                <Text className="iconfont iconmore"></Text>
                              </Text>
                            </View>
                            <View className="seekingContent">
                              <View className="seekingSubContent" onClick={() => navoDetail(el)}>
                                {isToggleStatus && renderAllText(el.seekingContent)}
                                {!isToggleStatus && renderText(el.seekingContent)}
                              </View>
                              {el.seekingContent.length > 80 && !isToggleStatus && (
                                <View
                                  className="seekingToggle"
                                  onClick={e => {
                                    e.stopPropagation()
                                    expandSingle(el.kid)
                                  }}>
                                  <Text className="iconfont iconicon-down"></Text> 展开
                                </View>
                              )}
                              {isToggleStatus && el.seekingContent.length > 80 && (
                                <View
                                  className="seekingToggle"
                                  onClick={e => {
                                    e.stopPropagation()
                                    expandSingle(el.kid)
                                  }}>
                                  <Text className="iconfont iconicon-up"></Text> 收起
                                </View>
                              )}
                              {el.userPhoto && (
                                <Image
                                  onClick={() => {
                                    Taro.previewImage({
                                      current: el.userPhoto,
                                      urls: [el.userPhoto],
                                    })
                                  }}
                                  className="seekingImg"
                                  mode="widthFix"
                                  webp
                                  src={
                                    el.userPhoto +
                                    '&x-oss-process=image/resize,m_fill,h_0,w_630/format,webp'
                                  }
                                />
                              )}
                            </View>
                            {((userInfo && userInfo.gender == 1 && el.gender == 2) ||
                              (userInfo && userInfo.gender == 2 && el.gender == 1)) && (
                              <View
                                className="seekingOper"
                                style={{
                                  color: el.gender == 1 ? `${MaleBg[index]}` : `${FeMaleBg[index]}`,
                                }}
                                onClick={e => {
                                  e.stopPropagation()
                                  inviteBlind(el)
                                }}>
                                {userInfo && userInfo.gender == 1 && el.gender == 2 && (
                                  <Text>邀她相亲</Text>
                                )}

                                {userInfo && userInfo.gender == 2 && el.gender == 1 && (
                                  <Text>邀他相亲</Text>
                                )}
                              </View>
                            )}
                            {/* <View
                              className="seekingOper"
                              onClick={() => {
                                Taro.navigateTo({
                                  url: `/pages/OuterPage/index?uri=hhttps://a.app.qq.com/o/simple.jsp?pkgname=com.yryz.lovelorn`,
                                })
                              }}>
                              打开app
                            </View> */}
                            {activeIndex == 1 && (
                              <Image
                                src={require('../../assets/seeking/male.png')}
                                className="seekingDot"
                              />
                            )}
                            {activeIndex == 2 && (
                              <Image
                                src={require('../../assets/seeking/female.png')}
                                className="seekingDot"
                              />
                            )}
                          </View>
                        )
                      })}
                  </PullDownUp>
                </AtTabsPane>
              )
            })}
          </AtTabs>
        </View>
        <MarriageBox
          isShow={isShow}
          userInfo={userInfo}
          onclose={() => {
            closeDialoge()
          }}
        />
        <ABlindDateBox
          isHide={isHide}
          seekingId={seekingId}
          onclose={() => {
            closeDialoge()
          }}
        />

        <View
          className="applyMarrige"
          onClick={() => {
            setIsShow(true)
          }}>
          <Image className="applyImg" src={require('../../assets/seeking/apply.png')} />
        </View>
        {scrollHeight > 1200 && (
          <View
            onClick={() => {
              Taro.pageScrollTo({
                scrollTop: -10,
              })
              setScrollTop(Math.random(0, 1))
            }}>
            <BackTop />
          </View>
        )}
      </View>
    </CanvasPageContext.Provider>
  )
}

Home.config = {
  navigationBarTitleText: '征婚',
  navigationBarBackgroundColor: '#F9F9F9',
}

export default Home
